package cc.rengu.igas.momp.core.service.trans;

import cc.rengu.igas.momp.common.constant.CommonConstant;
import cc.rengu.igas.momp.common.dao.CouponInfoMapper;
import cc.rengu.igas.momp.common.dao.impl.CouponInfoMapperImpl;
import cc.rengu.igas.momp.common.entity.TMCouponInfo;
import cc.rengu.igas.momp.common.enums.RespCodeEnum;
import cc.rengu.igas.momp.facade.bean.QueryCouponInfoByCustomerBean;
import cc.rengu.igas.momp.facade.request.QueryCouponInfoByCustomerRequest;
import cc.rengu.igas.momp.facade.response.QueryCouponInfoByCustomerResponse;
import cc.rengu.oltp.service.base.RadpService;
import cc.rengu.oltp.service.common.constant.TreeNodeConstant;
import cc.rengu.oltp.service.common.enums.ChannelEnum;
import cc.rengu.oltp.service.common.enums.OltpRpcdEnum;
import cc.rengu.oltp.service.model.BizException;
import cc.rengu.oltp.service.model.BizResponse;
import cc.rengu.oltp.utility.bean.PageInfo;
import cc.rengu.oltp.utility.bean.PageResult;
import cc.rengu.oltp.utility.util.ConvertUtil;
import cc.rengu.oltp.utility.util.XmlTreeUtil;
import cc.rengu.utility.base.StringUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 卡券信息查询功能实现
 *
 * @author liujinan
 * @date 2021/1/18 15:18
 */
public class QueryCouponInfoByCustomerService extends RadpService {

    private String globalInstId;
    private String globalQueryType;
    private String globalQueryRole;
    private String globalQueryId;
    private String globalQueryOrgId;
    private String globalMcNo;
    private String pageIndex;
    private String pageSize;
    private String globalClaimUser;
    private String globalCouponStatus;
    private String globalChannelId;

    @Override
    protected int bizInit(String s) {
        return 0;
    }

    @Override
    protected int bizProcess(String s, int i) {

        XmlTreeUtil xmlTreeUtil = new XmlTreeUtil();

        try {
            QueryCouponInfoByCustomerRequest queryCouponInfoByCustomerRequest = new QueryCouponInfoByCustomerRequest();
            ConvertUtil.convertOutput(queryCouponInfoByCustomerRequest);

            QueryCouponInfoByCustomerResponse queryCouponInfoByCustomerResponse = new QueryCouponInfoByCustomerResponse();
            queryCouponInfoByCustomerResponse.setHeader(queryCouponInfoByCustomerRequest.getHeader());
            BizResponse<QueryCouponInfoByCustomerResponse> bizResponse = new BizResponse<>();
            bizResponse.setResult(queryCouponInfoByCustomerResponse);

            /* 请求报文检查 */
            messageValidation(queryCouponInfoByCustomerRequest);

            // 服务调用
            BizResponse<QueryCouponInfoByCustomerResponse> bizResponseNew = queryCouponDetailInfoList(queryCouponInfoByCustomerResponse);

            ConvertUtil.convertInput(bizResponseNew.getResult());

        } catch (BizException e) {
            try {
                xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.RESP_CODE, e.getCode());
                xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.RESP_DESC, e.getMessage());
            } catch (Exception e1) {
                rglog.error(StringUtil.ExceptionToString(e1));
            }
        } catch (Exception e) {
            rglog.error(StringUtil.ExceptionToString(e));
            try {
                xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.RESP_CODE, OltpRpcdEnum.OLTP_PROCESS_ERROR.getRespCode());
                xmlTreeUtil.setXmlTreeStringValue(TreeNodeConstant.RESP_DESC, OltpRpcdEnum.OLTP_PROCESS_ERROR.getRespDesc());
            } catch (Exception e1) {
                rglog.error(StringUtil.ExceptionToString(e1));
            }
        }

        return CommonConstant.PROCESS_SUCCESS;
    }

    @Override
    protected int bizTerminate(String s) {
        return 0;
    }


    /**
     * 查询卡券详细信息
     * 用户可以查询自己已领取的营销活动的卡券信息
     *
     * @param queryCouponInfoByCustomerResponse 卡券类活动详情查询接口应答报文
     * @return cc.rengu.oltp.service.model.BizResponse<cc.rengu.igas.momp.facade.response.QueryCouponMcDetailInfoResponse> 卡券类活动详情查询接口应答报文
     * @throws Exception 异常信息
     * @author liujinan
     * @since 2021/1/18 14:50
     */
    private BizResponse<QueryCouponInfoByCustomerResponse> queryCouponDetailInfoList(QueryCouponInfoByCustomerResponse queryCouponInfoByCustomerResponse) throws Exception {

        BizResponse<QueryCouponInfoByCustomerResponse> bizResponse = new BizResponse<>();

        TMCouponInfo tMCouponInfo = new TMCouponInfo();
        //机构编码
        tMCouponInfo.setInstId(globalInstId);
        //营销活动编号
        tMCouponInfo.setMcNo(globalMcNo);
        //领取人
        tMCouponInfo.setClaimUserId(globalClaimUser);
        //卡券状态
        tMCouponInfo.setCouponStatus(globalCouponStatus);
        //渠道标识
        tMCouponInfo.setRemark1(globalChannelId);

        /* 用户查询卡券信息表 */
        queryCouponMcDetailInfoByUser(queryCouponInfoByCustomerResponse, tMCouponInfo);

        bizResponse.setRspSysId(ChannelEnum.MOMP.getChannelType());
        bizResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        bizResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());

        queryCouponInfoByCustomerResponse.setRespCode(RespCodeEnum.TRANS_SUCCESS.getRespCode());
        queryCouponInfoByCustomerResponse.setRespDesc(RespCodeEnum.TRANS_SUCCESS.getRespDesc());
        bizResponse.setResult(queryCouponInfoByCustomerResponse);

        return bizResponse;
    }


    /**
     * 用户查询已领取卡券信息
     *
     * @param queryCouponInfoByCustomerResponse 卡券信息查询接口应答对象
     * @param tMCouponInfo                      卡券查询使用实体类入参
     * @throws Exception 异常信息
     * @author liujinan
     * @date 2021/1/18 19:23
     */
    private void queryCouponMcDetailInfoByUser(QueryCouponInfoByCustomerResponse queryCouponInfoByCustomerResponse, TMCouponInfo tMCouponInfo) throws Exception {

        /* 查询指定营销活动所有卡券明细 */
        if (CommonConstant.MINUS_ONE_COMMON_CONSTANT.equals(pageIndex)) {
            /* 不分页查询流程 */
            List<TMCouponInfo> couponInfoList = getUserCouponListInfo(tMCouponInfo);

            if (null == couponInfoList || couponInfoList.isEmpty()) {
                queryCouponInfoByCustomerResponse.setTotalPage(CommonConstant.ZERO_COMMON_CONSTANT);
                queryCouponInfoByCustomerResponse.setTotalRows(CommonConstant.ZERO_COMMON_CONSTANT);
            } else {
                /* 查询到数据 */
                List<QueryCouponInfoByCustomerBean> couponListInfoBeanList = couponInfoList.stream().map(this::convertCouponInfo).collect(Collectors.toList());
                queryCouponInfoByCustomerResponse.setCouponInfoList(couponListInfoBeanList);
                queryCouponInfoByCustomerResponse.setTotalPage(CommonConstant.ONE_COMMON_CONSTANT);
                queryCouponInfoByCustomerResponse.setTotalRows(Integer.toString(couponListInfoBeanList.size()));
            }

        } else {
            /* 分页查询流程 */
            PageInfo pageInfo = new PageInfo();
            pageInfo.setPageIndex(Integer.parseInt(pageIndex));
            pageInfo.setPageSize(Integer.parseInt(pageSize));
            PageResult pageResult;

            pageResult = getUserCouponListInfoPage(tMCouponInfo, pageInfo);

            /* 拼接交易信息 */
            List<TMCouponInfo> couponInfoList = new ArrayList<>();
            if (null == pageResult || null == pageResult.getPageInfo() || null == pageResult.getResult() || pageResult.getResult().isEmpty()) {
                rglog.info("根据查询条件查询到0条卡券信息!");

                queryCouponInfoByCustomerResponse.setTotalPage(CommonConstant.ZERO_COMMON_CONSTANT);
                queryCouponInfoByCustomerResponse.setTotalRows(CommonConstant.ZERO_COMMON_CONSTANT);
            } else {

                for (Object object : pageResult.getResult()) {
                    couponInfoList.add((TMCouponInfo) object);
                }

                rglog.info("卡券查询，卡券总数量 SIZE=<{}>", pageResult.getResult().size());

                List<QueryCouponInfoByCustomerBean> couponListInfoBeanList = couponInfoList.stream().map(this::convertCouponInfo).collect(Collectors.toList());
                queryCouponInfoByCustomerResponse.setCouponInfoList(couponListInfoBeanList);

                queryCouponInfoByCustomerResponse.setTotalPage(Integer.toString(pageResult.getPageInfo().getTotalPage()));
                queryCouponInfoByCustomerResponse.setTotalRows(Integer.toString(pageResult.getPageInfo().getTotalRows()));
            }
        }
    }


    /**
     * 用户查询自己所有的卡券列表信息
     *
     * @throws Exception 异常信息
     * @author liujinan
     * @date 2021/1/18 15:47
     */
    private List<TMCouponInfo> getUserCouponListInfo(TMCouponInfo tMCouponInfo) throws Exception {

        CouponInfoMapper couponInfoMapper = new CouponInfoMapperImpl();

        return couponInfoMapper.getCouponListInfoByUser(tMCouponInfo);
    }

    /**
     * 用户分页查询卡券列表信息
     *
     * @param pageInfo 数据库操作分页实体类
     * @return cc.rengu.oltp.utility.bean.PageResult 查询结果列表
     * @throws Exception 异常信息
     * @author liujinan
     * @date 2021/1/18 22:46
     */
    private PageResult getUserCouponListInfoPage(TMCouponInfo tMCouponInfo, PageInfo pageInfo) throws Exception {

        CouponInfoMapper couponInfoMapper = new CouponInfoMapperImpl();
        return couponInfoMapper.getUserCouponListInfoPage(tMCouponInfo, pageInfo);
    }


    /**
     * 数据库实体类和接口实体类数据转换
     *
     * @param couponInfo
     * @return cc.rengu.igas.momp.facade.bean.QueryCouponInfoByCustomerBean
     * @throws Exception 异常信息
     * @author liujinan
     * @date 2021/1/18 15:04
     */
    private QueryCouponInfoByCustomerBean convertCouponInfo(TMCouponInfo couponInfo) {
        QueryCouponInfoByCustomerBean couponListInfoBean = new QueryCouponInfoByCustomerBean();

        /* 卡券编号 */
        couponListInfoBean.setCouponNo(couponInfo.getCouponNo());
        /* 卡券有效起始日期 */
        couponListInfoBean.setCouponStartDate(couponInfo.getCouponStartDate());
        /* 卡券有效结束日期 */
        couponListInfoBean.setCouponEndDate(couponInfo.getCouponEndDate());
        /* 领取日期 */
        couponListInfoBean.setClaimDate(couponInfo.getClaimDate());
        /* 领取时间 */
        couponListInfoBean.setClaimTime(couponInfo.getClaimTime());
        /* 卡券状态 */
        couponListInfoBean.setCouponStatus(couponInfo.getCouponStatus());
        /* 活动门槛 */
        couponListInfoBean.setCriteria(couponInfo.getCriteria());
        /* 卡券可抵扣金额 */
        couponListInfoBean.setCouponAmt(couponInfo.getCouponAmt());
        /* 购买标志 */
        couponListInfoBean.setPurchaseFlag(couponInfo.getPurchaseFlag());
        /* 购买金额 */
        couponListInfoBean.setPurchaseAmt(couponInfo.getPurchaseAmt());
        /* 核销时间 */
        couponListInfoBean.setRedeemTime(couponInfo.getRedeemTime());

        return couponListInfoBean;
    }


    /**
     * 报文检查
     *
     * @param queryCouponInfoByCustomerRequest 卡券信息查询接口请求对象
     * @author liujinan
     * @date 2021/1/18 10:53
     */
    private void messageValidation(QueryCouponInfoByCustomerRequest queryCouponInfoByCustomerRequest) {

        /* 检查交易日期 */
        if (StringUtil.isNullorEmpty(queryCouponInfoByCustomerRequest.getHeader().getTransDate())) {
            rglog.error("交易日期必须出现!");
            throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
        }

        /* 检查交易时间 */
        if (StringUtil.isNullorEmpty(queryCouponInfoByCustomerRequest.getHeader().getTransTime())) {
            rglog.error("交易时间必须出现!");
            throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
        }

        /* 检查机构标识 */
        if (StringUtil.isNullorEmpty(queryCouponInfoByCustomerRequest.getHeader().getInstId())) {
            rglog.error("机构标识必须出现!");
            throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
        } else {
            globalInstId = queryCouponInfoByCustomerRequest.getHeader().getInstId();
        }

        /* 检查交易流水号 */
        if (StringUtil.isNullorEmpty(queryCouponInfoByCustomerRequest.getHeader().getTraceNo())) {
            rglog.error("交易流水号必须出现!");
            throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
        }

        /* 检查查询类型 */
        if (StringUtil.isNullorEmpty(queryCouponInfoByCustomerRequest.getQueryType())) {
            rglog.error("查询类型必须出现!");
            throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
        } else {
            globalQueryType = queryCouponInfoByCustomerRequest.getQueryType();
        }

        /* 检查查询主体 */
        if (StringUtil.isNullorEmpty(queryCouponInfoByCustomerRequest.getQueryId())) {
            rglog.error("查询主体必须出现!");
            throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
        } else {
            globalQueryId = queryCouponInfoByCustomerRequest.getQueryType();
        }

        /* 检查查询主体所属机构 */
        if (StringUtil.isNullorEmpty(queryCouponInfoByCustomerRequest.getQueryOrgId())) {
            rglog.error("查询主体所属机构必须出现!");
            throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
        } else {
            globalQueryOrgId = queryCouponInfoByCustomerRequest.getQueryOrgId();
        }

        /* 检查查询主体角色*/
        if (StringUtil.isNullorEmpty(queryCouponInfoByCustomerRequest.getQueryRole())) {
            rglog.error("查询主体角色必须出现!");
            throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
        } else {
            globalQueryRole = queryCouponInfoByCustomerRequest.getQueryRole();
        }

        /* 领取人 */
        if (!StringUtil.isNullorEmpty(queryCouponInfoByCustomerRequest.getClaimUser())) {
            globalClaimUser = queryCouponInfoByCustomerRequest.getClaimUser();
        }

        /* 卡券状态 */
        if (!StringUtil.isNullorEmpty(queryCouponInfoByCustomerRequest.getCouponStatus())) {
            globalCouponStatus = queryCouponInfoByCustomerRequest.getCouponStatus();
        }

        /* 当前页数 */
        if (StringUtil.isNullorEmpty(queryCouponInfoByCustomerRequest.getPageIndex())) {
            rglog.error("当前页数必须出现!");
            throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
        } else {
            pageIndex = queryCouponInfoByCustomerRequest.getPageIndex();
        }

        /* 页显示记录数 */
        if (StringUtil.isNullorEmpty(queryCouponInfoByCustomerRequest.getPageSize())) {
            rglog.error("页显示记录数必须出现!");
            throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
        } else {
            pageSize = queryCouponInfoByCustomerRequest.getPageSize();
        }

        /* 检查渠道标识 */
        if (StringUtil.isNullorEmpty(queryCouponInfoByCustomerRequest.getChannelId())) {
            rglog.error("渠道标识必须出现!");
            throw new BizException(RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespCode(), RespCodeEnum.MSG_VALID_CHECK_ERROR.getRespDesc());
        } else {
            globalChannelId = queryCouponInfoByCustomerRequest.getChannelId();
        }
    }
}
